package servlet;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "RegisterServlet",urlPatterns = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = request.getParameter("username");
        String pwd = request.getParameter("pwd");
//        String pwd2 = request.getParameter("pwd2");
//        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        String png = request.getParameter("png");

        User user = new User();

//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//          df.format(new Date());
        user.setUName(name);
        user.setUPass(pwd);
        user.setGender(Integer.parseInt(sex));
        user.setHead(png);
        user.setRegTime(new Date());//当前时间

        UserService userService= new UserServiceImpl();
        boolean flag = false;
        flag = userService.register(user);
        UserService userservice  = new UserServiceImpl();
        User checkuser = userservice.login(name);
        if(checkuser!=null){
            if(flag){
                System.out.println("注册成功！");
                response.sendRedirect("login.jsp");
            }else{
                System.out.println("注册失败");
                request.setAttribute("msg", "注册失败");
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }
        }else{
            System.out.println("用户已存在！");
                request.setAttribute("msg", "用户已存在！");
                request.getRequestDispatcher("register.jsp").forward(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
